package com.bdbit.ChargingStation.wx;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AesUtil {
    private static final String ALGORITHM = "AES/GCM/NoPadding";
    private static final int TAG_LENGTH_BIT = 128;
    private final byte[] apiV3Key;

    public AesUtil(byte[] apiV3Key) {
        this.apiV3Key = apiV3Key;
    }

    public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
            throws Exception {
        try {
            // 检查参数
            if (apiV3Key == null || apiV3Key.length != 32) {
                throw new IllegalArgumentException("无效的APIv3密钥长度");
            }
            if (nonce == null || nonce.length != 12) {
                throw new IllegalArgumentException("Nonce长度必须为12字节");
            }

            // 初始化Cipher
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(apiV3Key, "AES");
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);

            // 设置关联数据
            if (associatedData != null) {
                cipher.updateAAD(associatedData);
            }

            // Base64解码并解密
            byte[] ciphertextBytes = Base64.getDecoder().decode(ciphertext);
            byte[] plaintext = cipher.doFinal(ciphertextBytes);

            return new String(plaintext, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new Exception("AES解密失败: " + e.getMessage(), e);
        }
    }
}